//
//  HYBDPanFIleListController.m
//  XPlayer
//
//  Created by 张水 on 2023/9/15.
//

#import "HYBDPanFIleListController.h"
#import "HYBDPanFileListCell.h"
#import "HYBDPanFileListViewModel.h"
#import "HYVideoRoomViewController.h"
#import "HYPDFPreviewController.h"
#import <HYUIKit/HYWKWebViewController.h>
#import "HYPreviewImageController.h"
#import "HYBDpanListView.h"
#import <HYUIKit/HYPopMenu.h>
#import "HYBDPanCollectionView.h"
#import "HYAudioRoomViewController.h"
#import "HYVideoViewModel.h"
#import "XDSReaderHeader.h"
#import "HYHomeMainView.h"
@interface HYBDPanFIleListController ()<HYWebProtocol>

@property (nonatomic, strong) HYBDPanFileListViewModel *viewModel;

@property (nonatomic, strong) NSMutableArray *photos;

@property (nonatomic, strong) HYHomeMainView *mainView;

@property (nonatomic, strong) HYHomeMainView *videoView;

@property (nonatomic, strong) HYHomeMainView *audioView;

@property (nonatomic, strong) HYHomeMainView *fileView;

@property (nonatomic, strong) HYHomeMainView *picView;

@property (nonatomic, strong) HYHomeMainView *otherView;

@end

@implementation HYBDPanFIleListController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.isHome) {
        self.navigationBarView.titleLabel.text = NSLocalizedString(@"百度云盘", nil);
        self.navigationBarView.navagationBarStyle = Left_right_button_show;
        [self.navigationBarView.rightButton setTitle:NSLocalizedString(@"退出", nil)forState:UIControlStateNormal];
    }else{
        self.navigationBarView.titleLabel.text = self.subPathName;
    }
    self.view.backgroundColor = AppBgThemeColor;
    
    [self configUI];
    [self bindSignal];
    [self loadData];
}

- (void)rightButtonClick
{
    @weakify(self);
    [[BDPanOauthManager manager] quitBDpan:^{
        @strongify(self);
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
}

- (void)configUI
{
    CGFloat hToolViewY = NAVIGATIONBAR_HEIGHT+2.5;
    CGFloat hToolHeight = [self preferredCategoryViewHeight];
    CGFloat tContainerHeight = kMainScreenHeight-hToolViewY-HOME_BAR_HEIGHT;
    CGFloat tContainerY = hToolViewY+hToolHeight;
    self.titles = @[NSLocalizedString(@"全部", nil),NSLocalizedString(@"视频", nil),NSLocalizedString(@"音频", nil),NSLocalizedString(@"文件", nil),NSLocalizedString(@"图片", nil),NSLocalizedString(@"其他", nil)];
    self.myCategoryView.titles = self.titles;
    self.myCategoryView.frame = CGRectMake(0, hToolViewY, kScreenWidth, hToolHeight);
    self.listContainerView.frame = CGRectMake(0, tContainerY, kScreenWidth, tContainerHeight);
    [self.view addSubview:self.myCategoryView];
    [self.view addSubview:self.listContainerView];
}

- (void)loadData
{
    NSString *path = @"";
    if (self.isHome) {
        path = @"/";
    }else{
        path = self.subPath;
    }
    @weakify(self);
    [self.viewModel loadPathDataWith:path listData:^{
        @strongify(self);
        [self.viewModel.updatedContentSignal sendNext:@""];
    }];
}


- (void)bindSignal
{
    @weakify(self);
    [self.viewModel.videoPlaySubject subscribeNext:^(HYVideoViewModel *videoModel) {
        @strongify(self);
        [self showVideoWithPlayerViewModel:videoModel];
    }];
    [self.viewModel.CellClickSubject subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
        HYBDPanFileModelList *fileMeta = tuple.first;
        NSIndexPath *indexPath = tuple.second;
        [self cellClickAction:fileMeta indexPath:indexPath];
    }];
    [self.viewModel.CollectionCellClickSubject subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
        HYBDPanFileModelList *fileMeta = tuple.first;
        NSIndexPath *indexPath = tuple.second;
        [self cellClickAction:fileMeta indexPath:indexPath];
    }];
}

- (void)hy_closeCurrentPage
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)cellClickAction:(HYBDPanFileModelList *)fileMeta indexPath:(NSIndexPath *)indexPath
{
    NSString *urlString = [NSString stringWithFormat:@"%@&access_token=%@",fileMeta.dlink,[BDPanOauthManager manager].accessToken];
    switch (fileMeta.category) {
        case BDPanFileTypeVideo:
        {
            [self.viewModel fetchVideoPlayUrlWithIndexPath:indexPath withFileType:BDPanFileTypeVideo];
        }
            break;
        case BDPanFileTypeAudio:
        {
            [self showAudioWith:indexPath with:fileMeta];
        }
            break;
        case BDPanFileTypePhoto:
        {
            [self showPhotoBrowser:indexPath];
        }
            break;
        case BDPanFileTypeDocument:
        {
            NSMutableArray *array = [NSMutableArray arrayWithArray:[fileMeta.filename componentsSeparatedByString:@"."]];
            NSString *filetype = [NSString stringWithFormat:@"%@", array.hy_lastObject];
            if([filetype isEqualToString:@"pdf"] || [filetype isEqualToString:@"PDF"]) {
                HYPDFPreviewController *pdfController = [[HYPDFPreviewController alloc]init];
                pdfController.urlString = urlString;
                pdfController.fileName = fileMeta.filename;
                [self.navigationController pushViewController:pdfController animated:YES];
            }else if([@[@"epub",@"txt"] containsObject:filetype]){
                [self previewInternet:fileMeta.filename withPath:urlString];
            }else {
                HYWKWebViewController *webVC = [[HYWKWebViewController alloc]init];
                webVC.navigationBarView.navagationBarStyle = None_button_show;
                webVC.delegate = self;
                webVC.noShowClose = NO;
                webVC.staticNavTitle = fileMeta.filename;
                webVC.netUrl = urlString;
                webVC.modalPresentationStyle = UIModalPresentationFullScreen;
                [self presentViewController:webVC animated:YES completion:nil];
            }
        }
            break;
            
        default:
            break;
    }
    if ([fileMeta.isdir isEqualToString:@"1"]) {
        HYBDPanFIleListController *listVC = [[HYBDPanFIleListController alloc]init];
        listVC.subPath = fileMeta.path;
        listVC.subPathName = fileMeta.server_filename;
        listVC.isHome = NO;
        [self.navigationController pushViewController:listVC animated:YES];
    }
}

- (void)showPhotoBrowser:(NSIndexPath *)indexPath
{
    NSArray *images = [self.viewModel.picList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(HYBDPanFileModelList * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return evaluatedObject.category == BDPanFileTypePhoto;
    }]];
    NSMutableArray *photoMetas = [NSMutableArray array];
    for (NSInteger i = 0; i < images.count; i++) {
        HYBDPanFileModelList *fileMeta = images[i];
        [photoMetas addObject:fileMeta];
    }
    HYBDPanFileModelList *didSelectFileMeta = [self.viewModel.picList objectAtIndex:indexPath.row];
    NSInteger index = [photoMetas indexOfObject:didSelectFileMeta];
    [self showBrowserWithImages:photoMetas currentIndex:index];
}

- (void)showBrowserWithImages:(NSArray *)imageArray currentIndex:(NSUInteger)currentIndex
{
    [self.photos removeAllObjects];
    if (imageArray && [imageArray count] > 0) {
        for (HYBDPanFileModelList *fileMeta in imageArray) {
            [self.photos hy_addObject:fileMeta.thumbs.url3];
        }
    }
    HYPreviewImageController *imageVc = [[HYPreviewImageController alloc] initWithImages:self.photos currentIndex:currentIndex];
    imageVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imageVc animated:YES completion:nil];
}

- (void)showAudioWith:(NSIndexPath *)indexPath with:(HYBDPanFileModelList *)fileMeta;
{
    NSArray *audios = [self.viewModel.audioList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(HYBDPanFileModelList * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return evaluatedObject.category == BDPanFileTypeAudio;
    }]];
    NSMutableArray *tmpAudios = [NSMutableArray array];
    for (int i = 0; i < audios.count; i++) {
        HYBDPanFileModelList *fileMeta = audios[i];
        [tmpAudios hy_addObject:fileMeta.fs_id];
    }
    NSMutableArray *tmpfileMetas = [NSMutableArray array];
    @weakify(self);
    [self requestFids:tmpAudios bDFileInfo:^(NSArray *fileMetas) {
        @strongify(self);
        HYVideoModel *currentModel;
        for (int i = 0 ; i < fileMetas.count; i++) {
            HYBDPanFileModelList *fileModel = fileMetas[i];
            HYVideoModel *model = [[HYVideoModel alloc]init];
            model.videoUrl = [NSString stringWithFormat:@"%@&access_token=%@",fileModel.dlink,[BDPanOauthManager manager].accessToken];
            model.videoTitle = fileModel.filename;
            model.isAudio = YES;
            if([fileModel.fs_id isEqualToString:fileMeta.fs_id]){
                currentModel = model;
                currentModel.isSelect = YES;
            }
            [tmpfileMetas hy_addObject:model];
        }
        if(currentModel){
            [self playAudioWithCurrentAudioModel:currentModel withAudios:tmpfileMetas];
        }
    }];
}
- (void)requestFids:(NSMutableArray *)fids bDFileInfo:(BDFileInfo)bDFileInfo
{
    [[BDPanOauthManager manager] searchFids:fids bDFileInfo:^(id responseObject) {
        HYBDPanFileModel *fileModel = [HYBDPanFileModel modelWithJson:responseObject];
        NSArray *array = [fileModel.list sortedArrayUsingComparator:^NSComparisonResult(HYBDPanFileModelList *obj1, HYBDPanFileModelList *obj2) {
          //降序
          NSComparisonResult result = [obj1.server_mtime  compare:obj2.server_mtime];
          return -result;
        }];
        if (bDFileInfo) {
            bDFileInfo(array);
        }
    }];
}

- (void)playAudioWithCurrentAudioModel:(HYVideoModel *)audioModel withAudios:(NSArray *)audios
{
    HYVideoPlayerConfig *config = [[HYVideoPlayerConfig alloc]init];
    config.isBasePlayer = YES;
    config.currentVideoModel = audioModel;
    config.videoSoucres = audios;
    config.isAudioMode = YES;
    HYVideoViewModel *viewModel = [[HYVideoViewModel alloc]initWithFolderIdentification:@"baidu-vplayer" isPrivate:NO videoConfig:config];
    HYAudioRoomViewController *audioVC = [[HYAudioRoomViewController alloc]initWithViewModel:viewModel];
    [self.navigationController pushViewController:audioVC animated:YES];
}

- (void)showVideoWithPlayerViewModel:(HYVideoViewModel *)viewModel
{
    HYVideoRoomViewController *videoVC = [[HYVideoRoomViewController alloc]initWithViewModel:viewModel];
    [self.navigationController pushViewController:videoVC animated:YES];
}

- (void)previewInternet:(NSString *)fileName withPath:(NSString *)path{
    //判断是否存在
    if([self isFileExist:fileName]) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
        [self preViewFile:url];
    }else {
        NSDictionary *dic = [NSDictionary dictionaryWithObject:@"pan.baidu.com" forKey:@"User-Agent"];
        [HYHub loadMessage:NSLocalizedString(@"加载数据中", nil)];
        NSURLSessionDownloadTask *downloadTask = [HYRequestBaseHelper download:path parameters:nil headers:dic progress:^(NSProgress *downloadProgress) {
            NSLog(@"当前下载进度为:%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            if(response){
               [HYHub dismiss];
               [self preViewFile:filePath];
            }else{
                [HYHub showMessage:NSLocalizedString(@"加载失败", nil)];
                [HYHub dismiss];
            }

        }];
        [downloadTask resume];
    }
}

- (void)preViewFile:(NSURL *)url
{
    [[XDSReadManager sharedManager] updateReadRect];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HYHub showMessage:NSLocalizedString(@"正在加载中,请耐心等待", nil)];
        XDSBookModel *bookModel = [XDSBookModel getLocalModelWithURL:url];
        dispatch_async(dispatch_get_main_queue(), ^{
            [HYHub dismiss];
            XDSReadPageViewController *pageView = [[XDSReadPageViewController alloc] init];
            [[XDSReadManager sharedManager] setResourceURL:url];//文件位置
            [[XDSReadManager sharedManager] setBookModel:bookModel];
            [[XDSReadManager sharedManager] setRmDelegate:pageView];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:pageView animated:YES];
        });
    });
}
//判断文件是否已经在沙盒中存在
-(BOOL)isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}

#pragma mark - JXCategoryListContentViewDelegate
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index
{
    HYHomeMainView *mainView;
    if(index == 0){
        mainView = [[HYHomeMainView alloc]initWithBDViewModel:self.viewModel fileType:BDPanFileTypeALL];
        self.mainView = mainView;
    }else if (index == 1){
        mainView = [[HYHomeMainView alloc]initWithBDViewModel:self.viewModel fileType:BDPanFileTypeVideo];
        self.videoView = mainView;
    }else if (index == 2){
        mainView = [[HYHomeMainView alloc]initWithBDViewModel:self.viewModel fileType:BDPanFileTypeAudio];
        self.audioView = mainView;
    }else if (index == 3){
        mainView = [[HYHomeMainView alloc]initWithBDViewModel:self.viewModel fileType:BDPanFileTypeDocument];
        self.fileView = mainView;
    }else if (index == 4){
        mainView = [[HYHomeMainView alloc]initWithBDViewModel:self.viewModel fileType:BDPanFileTypePhoto];
        self.picView = mainView;
    }else if (index == 5){
        mainView = [[HYHomeMainView alloc]initWithBDViewModel:self.viewModel fileType:BDPanFileTypeOther];
        self.otherView = mainView;
    }
    return mainView;
}


- (HYBDPanFileListViewModel *)viewModel
{
    if(_viewModel == nil){
        _viewModel = [[HYBDPanFileListViewModel alloc]init];
    }
    return  _viewModel;
}

- (NSMutableArray *)photos
{
    if (_photos == nil) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}
@end
